package com.bai.oss.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.bai.oss.service.OssService;
import com.bai.oss.utils.ConstantPropertiesUtils;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

@Service
public class OssServiceImpl implements OssService {

    //上传头像
    @Override
    public String uploadFileAvatar(MultipartFile file) {
        // 工具类获取值
        String endpoint = ConstantPropertiesUtils.ENDPOINT;
        String accessKeyId = ConstantPropertiesUtils.KEYID;
        String accessKeyIdSecret = ConstantPropertiesUtils.KEYSECRET;
        String bucketName = ConstantPropertiesUtils.BUCKETNAME;


        try {
            // 创建OSSClient实例。
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeyIdSecret);
            //上传文件流
            InputStream inputStream = file.getInputStream();
            String s = UUID.randomUUID().toString().replace("-", "");
            //获取文件名称
            String filename = s+file.getOriginalFilename() ;
            //获取当前日期
            String date = new DateTime().toString("yyyy/MM/dd");
            String fileName = date + "/" + filename;
            //调用oss方法实现上传
            ossClient.putObject(bucketName, fileName, inputStream);
            ossClient.shutdown();
            //上传文件路径之后返回
            //上传到阿里云oss路径拼接
            String url = "https://" + bucketName + "." + endpoint + "/" + fileName;
            return url;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}
